<template>
  <div class="user-form">
    <h2>{{ formData.userID ? "编辑用户" : "新增用户" }}</h2>
    <form @submit.prevent="saveUser">
      <div>
        <label for="username">用户名:</label>
        <input id="username" v-model="formData.username" type="text" required />
      </div>
      <div>
        <label for="fullName">真实姓名:</label>
        <input id="fullName" v-model="formData.fullName" type="text" required />
      </div>
      <div>
        <label for="role">角色:</label>
        <select id="role" v-model="formData.role" required>
          <option value="member">普通用户</option>
          <option value="admin">管理员</option>
        </select>
      </div>
      <div>
        <label for="email">邮箱:</label>
        <input id="email" v-model="formData.email" type="email" required />
      </div>
      <div>
        <label for="phone">电话:</label>
        <input id="phone" v-model="formData.phone" type="text" required />
      </div>
      <!-- 仅在编辑用户时显示密码输入 -->
      <div v-if="formData.userID">
        <label for="password">密码:</label>
        <input id="password" v-model="formData.password" type="password" />
      </div>
      <button type="submit">保存</button>
      <button type="button" @click="$emit('close')">取消</button>
    </form>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "UserForm",
  props: {
    user: Object,
  },
  data() {
    return {
      formData: {
        userID: null,
        username: "",
        fullName: "",
        role: "member", // 默认角色
        email: "",
        phone: "",
        password: "1234", 
      },
    };
  },
  watch: {
    user: {
      immediate: true,
      handler(newVal) {
        if (newVal) {
          this.formData = { ...newVal }; // 克隆对象，避免直接修改父组件数据
        } else {
          this.resetForm();
        }
      },
    },
  },
  methods: {
    saveUser() {
      const api = this.formData.userID ? "/user/update" : "/user/add";
      const method = this.formData.userID ? "put" : "post";

      axios[method](api, this.formData)
        .then(() => {
          alert("保存成功！");
          this.$emit("save"); // 通知父组件刷新列表
          this.$emit("close"); // 关闭弹窗
        })
        .catch((error) => {
          console.error("保存用户失败:", error);
          alert("保存失败，请检查输入！");
        });
    },
    resetForm() {
      // 重置表单数据为新增状态
      this.formData = {
        userID: null,
        username: "",
        fullName: "",
        role: "member",
        email: "",
        phone: "",
        password: "1234",
      };
    },
  },
};
</script>

<style scoped>
.user-form {
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 8px;
  width: 300px;
}

form div {
  margin-bottom: 10px;
}

label {
  display: block;
  margin-bottom: 5px;
}

input,
select {
  width: 100%;
  padding: 8px;
}
</style>
